package leetcode;

import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 描述:347. 前 K 个高频元素
 *
 * @author Madison You
 * @created 23:44
 */
public class Mid_347_TopKFrequent {

    public static void main(String[] args) {
        int[] ints = {5, 2, 5, 3, 5, 3, 1, 1, 3};
        new Mid_347_TopKFrequent().topKFrequent(ints, 2);
    }

    public int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        PriorityQueue<Map.Entry<Integer, Integer>> priorityQueue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            priorityQueue.add(entry);
            if (priorityQueue.size() > k) {
                priorityQueue.poll();
            }
        }
        int[] ints = new int[k];
        for (int i = 0; i < k; i++) {
            ints[i] = priorityQueue.poll().getKey();
        }
        return ints;
    }
}
